<?php
namespace RHX\Model\Table;

use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;

use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Where;
use Zend\Db\Sql\Expression;
use Zend\Db\Sql\Select;

use RHX\Model\Object\Transport;

class TransportTable extends AbstractTableGateway
{
    protected $table = 'rh_transport';
    
    public function __construct(Adapter $adapter)
    {
        $this->adapter = $adapter;
        $this->resultSetPrototype = new ResultSet();
        $this->resultSetPrototype->setArrayObjectPrototype(new Transport());
        $this->initialize();
    }
    
    public function getAll()
    {
        return $this->select();
    }
    
    public function getSelectList()
    {
	$rows = $this->select(function(Select $select) {
		    $select->order('libelle DESC');
		});
	$arr = array();
        // Parcours de la liste
	foreach ($rows as $t) {
	    $arr[$t->id] = $t->libelle;
	}

	return $arr;
    }
    
    public function get($id)
    {
        $id = (int)$id;
        $row	 = $this->select(array('id' => $id))
		->current();
        if(!$row)
            throw new \Exception("Impossible de trouver #$id");
        
        return $row;
    }
    
    public function save(Transport $transport)
    {
        $data = array(
            'libelle'       => $transport->libelle,
            'description'   => $transport->description,
            'valeur'        => $transport->valeur,
            'actif'         => $transport->actif,
        );
        $id	 = (int) $transport->id;
	if($id == 0)
            $this->insert($data);
        elseif($this->get($id))
            $this->update($data, array('id' => $id));
	else
            throw new \Exception("Impossible de trouver #$id");
        if($id == 0) return $this->lastInsertValue;
        else return $id;
    }

    /**
     * Efface les titres de transport correspondant
     *
     * @param int $id A effacer
     * @return int Nombre effacé
     */
    public function erase($id)
    {
        return $this->delete(array('id' => $id));
    }
}